const { Service } = require('egg');
const moment = require('moment');
const { v4: uuidV4 } = require('uuid');
const role_table = 'role';
const user_table = 'user';
class RoleService extends Service {
  // 查询角色列表
  async list(name, order, method, pageIndex = 1, pageSize = 10) {
    try {
      let promiseData = this.app.knex().select('t1.uuid', 't1.name', 't2.name as create_by', 't3.name as update_by',
        't1.update_time', 't1.create_time')
        .from(`${role_table} as t1`)
        .leftJoin(`${user_table} as t2`, () => {
          this.on('t2.uuid', '=', 't1.create_by');
        })
        .leftJoin(`${user_table} as t3`, () => {
          this.on('t3.uuid', '=', 't1.update_by');
        })
        .where('t1.is_delete', 0);
      if (name) {
        promiseData = promiseData.whereLike('t1.name', `%${name}%`);
      }

      promiseData = promiseData.orderBy(order, method).limit(pageSize).offset((Number(pageIndex) - 1) * Number(pageSize));

      const list = await promiseData;

      let promiseCount = this.app.knex(role_table).count({ id: 'id' }).where('is_delete', 0);

      if (name) {
        promiseCount = promiseCount.whereLike('name', `%${name}%`);
      }

      const count = await promiseCount;

      return {
        count: count[0].id,
        list,
      };
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 新增角色
  async insert(name) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      const instance = {
        name,
        uuid: uuidV4(),
        create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
        update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
        create_by: id,
        update_by: id,
        is_delete: 0,
      };

      const is_repeat = await this.app.knex().select('*').from(role_table)
        .where({ name });

      if (is_repeat) {
        throw new Error('当前角色名称重复');
      }

      const data = await this.app.knex(role_table).insert(instance).returning('id');
      instance.id = data[0];

      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 更新角色
  async update(name, uuid) {
    try {
      const time = moment();
      const { id } = this.ctx.session;

      const is_repeat = await this.app.knex().select('*').from(role_table)
        .where({ name })
        .whereNot({ uuid });

      if (is_repeat) {
        throw new Error('当前角色名称重复');
      }

      const instance = await this.app.knex(role_table).select('*').where({ uuid });
      instance.name = name;
      instance.update_time = moment(time).format('YYYY-MM-DD HH:mm:ss');
      instance.update_by = id;
      await this.app.knex(role_table).update(instance).where({ uuid });
      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 删除角色
  async delete(ids) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      await this.app.knex(role_table)
        .update({ is_delete: 1, update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'), update_by: id })
        .whereIn('uuid', ids)
        .andWhere({ is_delete: 0 });
      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  async initRole() {
    try {
      const super_admin_exist = await this.app.knex(role_table).select('uuid').where({ name: '超级管理员' })
        .first();
      const admin_exist = await this.app.knex(role_table).select('uuid').where({ name: '管理员' })
        .first();

      const list = [];

      if (!super_admin_exist) {
        list.push({
          uuid: uuidV4(),
          name: '超级管理员',
          create_by: '-1',
          update_by: '-1',
          is_delete: 0,
        });
      }

      if (!admin_exist) {
        list.push({
          uuid: uuidV4(),
          name: '管理员',
          create_by: '-1',
          update_by: '-1',
          is_delete: 0,
        });
      }


      if (list.length > 0) {
        await this.app.knex(role_table).insert(list);
      }
      return list;
    } catch (error) {
      throw error;
    }
  }
}

module.exports = RoleService;
